package cn.peifu.hrm.util;

import cn.peifu.hrm.exception.GlobalException;
import cn.peifu.hrm.to.LoginInfoTo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

public class LoginContext {
    public static LoginInfoTo getLogin(){
        SecurityContext context = SecurityContextHolder.getContext();
        if(context == null ){
            throw new GlobalException("认证错误！");
        }
        Authentication authentication = context.getAuthentication();
        if(authentication == null ){
            throw new GlobalException("认证错误！");
        }
        Object principal = authentication.getPrincipal();
        if(principal == null){
            throw new GlobalException("认证错误！");
        }
        return JSONObject.parseObject(JSONObject.toJSONString(principal),LoginInfoTo.class);
    }
}